package 链表;

// https://leetcode-cn.com/problems/merge-two-sorted-lists/
// 1->2->4 + 1->3->4 =>
// 1->1->2->3->4->5
public class _21_合并两个有序链表 {
    public static ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        }
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists2(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists2(l1, l2.next);
            return l2;
        }
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dynamicHead = new ListNode(0);
        ListNode newHead = dynamicHead;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                newHead.next = l1;
                l1 = l1.next;
                newHead = newHead.next;
            } else {
                newHead.next = l2;
                l2 = l2.next;
                newHead = newHead.next;
            }
        }
        if (l1 != null) {
            newHead.next = l1;
        } else {
            newHead.next = l2;
        }

        return dynamicHead.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(4);

        ListNode head2 = new ListNode(1);
        head2.next = new ListNode(3);
        head2.next.next = new ListNode(4);

//        ListNode newHead = mergeTwoLists(head, head2);
        ListNode newHead = mergeTwoLists2(head, head2);
        System.out.println(newHead);
    }
}
